<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.9.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring Cloud天气项目微服务,">










<meta name="description" content="本文学习从天气项目看Spring Cloud微服务治理第一章、第二章，包括：SpringBoot的简介、基于Springboot开发天气预报单体系统视频课程地址：https://coding.imooc.com/class/chapter/177.html项目代码地址： https://gitee.com/aiolos123/spring-cloud-weather">
<meta name="keywords" content="Spring Cloud天气项目微服务">
<meta property="og:type" content="article">
<meta property="og:title" content="【一】从天气项目看Spring Cloud微服务治理——基于Springboot开发天气预报单体系统">
<meta property="og:url" content="https://aiolos123.gitee.io/blog/2019/11/14/spring-cloud-weather-1/index.html">
<meta property="og:site_name" content="Aiolos">
<meta property="og:description" content="本文学习从天气项目看Spring Cloud微服务治理第一章、第二章，包括：SpringBoot的简介、基于Springboot开发天气预报单体系统视频课程地址：https://coding.imooc.com/class/chapter/177.html项目代码地址： https://gitee.com/aiolos123/spring-cloud-weather">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191114103354346.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191114144858042.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191114104855357.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191114141217894.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191115130316433.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191115125905884.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191118130148706.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191120175853773.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191121092757906.jpg">
<meta property="og:image" content="https://aiolos123.gitee.io/blog/images/20191121131042251.jpg">
<meta property="og:updated_time" content="2019-11-21T06:21:56.955Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="【一】从天气项目看Spring Cloud微服务治理——基于Springboot开发天气预报单体系统">
<meta name="twitter:description" content="本文学习从天气项目看Spring Cloud微服务治理第一章、第二章，包括：SpringBoot的简介、基于Springboot开发天气预报单体系统视频课程地址：https://coding.imooc.com/class/chapter/177.html项目代码地址： https://gitee.com/aiolos123/spring-cloud-weather">
<meta name="twitter:image" content="https://aiolos123.gitee.io/blog/images/20191114103354346.jpg">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://aiolos123.gitee.io/blog/2019/11/14/spring-cloud-weather-1/">





  <title>【一】从天气项目看Spring Cloud微服务治理——基于Springboot开发天气预报单体系统 | Aiolos</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Aiolos</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">记录我的成长点滴</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/blog/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/blog/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://aiolos123.gitee.io/blog/blog/2019/11/14/spring-cloud-weather-1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="aiolos">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/blog/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Aiolos">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">【一】从天气项目看Spring Cloud微服务治理——基于Springboot开发天气预报单体系统</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-11-14T05:59:13+08:00">
                2019-11-14
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/Spring-Cloud/" itemprop="url" rel="index">
                    <span itemprop="name">Spring Cloud</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>本文学习从天气项目看Spring Cloud微服务治理第一章、第二章，包括：SpringBoot的简介、基于Springboot开发天气预报单体系统<br>视频课程地址：<a href="https://coding.imooc.com/class/chapter/177.html" target="_blank" rel="noopener">https://coding.imooc.com/class/chapter/177.html</a><br>项目代码地址： <a href="https://gitee.com/aiolos123/spring-cloud-weather" target="_blank" rel="noopener">https://gitee.com/aiolos123/spring-cloud-weather</a></p>
<a id="more"></a>

<h2 id="本文中的关键技术点"><a href="#本文中的关键技术点" class="headerlink" title="本文中的关键技术点"></a>本文中的关键技术点</h2><ol>
<li>使用Redis读取与保存数据</li>
<li>使用HttpClient爬取JSON数据，并解析JSON数据为POJO对象</li>
<li>解析xml文件为POJO对象</li>
<li>使用Quartz Scheduler实现定时任务</li>
<li>集成并使用Thymeleaf模板引擎</li>
</ol>
<h2 id="扩展学习"><a href="#扩展学习" class="headerlink" title="扩展学习"></a>扩展学习</h2><ol>
<li>作者编写的Thymeleaf模板引擎的使用教程：<a href="https://waylau.gitbooks.io/thymeleaf-tutorial/" target="_blank" rel="noopener">https://waylau.gitbooks.io/thymeleaf-tutorial/</a></li>
<li>作者的另一门实战课程：《基于SpringBoot的企业级博客系统实战》</li>
</ol>
<h2 id="微服务的基石——SpringBoot简介"><a href="#微服务的基石——SpringBoot简介" class="headerlink" title="微服务的基石——SpringBoot简介"></a>微服务的基石——SpringBoot简介</h2><blockquote>
<p>spring框架的再次封装 -&gt; springboot</p>
</blockquote>
<p>springboot愿景：简化开发——抛弃传统JavaEE项目繁琐的配置、学习过程，让企业级开发过程变得简单！</p>
<p>springboot与其他框架的关系：<br><img src="/blog/images/20191114103354346.jpg" alt="springboot与其他框架的关系"></p>
<h3 id="通过MockMvc进行web项目的单元测试"><a href="#通过MockMvc进行web项目的单元测试" class="headerlink" title="通过MockMvc进行web项目的单元测试"></a>通过MockMvc进行web项目的单元测试</h3><p><img src="/blog/images/20191114144858042.jpg" alt="通过MockMvc进行web项目的单元测试"></p>
<h3 id="运行springboot项目的三种方式"><a href="#运行springboot项目的三种方式" class="headerlink" title="运行springboot项目的三种方式"></a>运行springboot项目的三种方式</h3><p>参考：<a href="https://blog.csdn.net/weixin_39999535/article/details/81477567" target="_blank" rel="noopener">https://blog.csdn.net/weixin_39999535/article/details/81477567</a></p>
<ol>
<li>java -jar xxx.jar</li>
<li>mvn spring-boot:run</li>
<li>IDE 右键</li>
</ol>
<h2 id="基于Springboot构建天气预报系统"><a href="#基于Springboot构建天气预报系统" class="headerlink" title="基于Springboot构建天气预报系统"></a>基于Springboot构建天气预报系统</h2><h3 id="天气预报单系统的功能"><a href="#天气预报单系统的功能" class="headerlink" title="天气预报单系统的功能"></a>天气预报单系统的功能</h3><ol>
<li>通过HTTPClient获取第三方接口的天气数据</li>
<li>通过Redis存储数据提升并发能力</li>
<li>通过定时器定时获取数据</li>
<li>为天气预报系统增加展示页面</li>
</ol>
<h3 id="天气预报系统开发准备"><a href="#天气预报系统开发准备" class="headerlink" title="天气预报系统开发准备"></a>天气预报系统开发准备</h3><ol>
<li><p>技术栈</p>
<blockquote>
<p>Appache HttpClient 4.5.10;RestTemplate;Spring Boot Web Starter;JDK8+;Maven3.5；Redis；<br>Spring Boot Data Redis Starter; Spring Boot Quartz Starter; Quartz Scheduler; Spring Boot Thymeleaf Starter 2.0.0.M4;Thymeleaf 3.0.7.RELEASE;Bootstrap 4.0.0-beta.2;</p>
</blockquote>
</li>
<li><p>天气预报免费数据来源<br>参考博客：<a href="https://blog.csdn.net/JON_QQ/article/details/101106375" target="_blank" rel="noopener">https://blog.csdn.net/JON_QQ/article/details/101106375</a></p>
</li>
</ol>
<figure class="highlight dts"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="symbol">http:</span><span class="comment">//wthrcdn.etouch.cn/weather_mini?city=沈阳</span></span><br><span class="line"><span class="meta"># 通过城市名字获得天气数据，json数据</span></span><br><span class="line"><span class="symbol">http:</span><span class="comment">//wthrcdn.etouch.cn/weather_mini?citykey=101070101</span></span><br><span class="line"><span class="meta"># 通过城市id获得天气数据，json数据</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/images/20191114104855357.jpg" alt="天气预报免费数据来源"></p>
<p><strong>注意：前两个url中的城市名称和key可以从第三个的citylist.xml文件中获取</strong></p>
<ol start="3">
<li><p>配置RestTemplate</p>
<figure class="highlight aspectj"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 配置RestTemplate的具体实现</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 我们已经加入了Apache Client的依赖</span></span><br><span class="line"><span class="comment"> * RestTemplate启动时默认从classpath中寻找这个依赖作为具体实现</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">RestConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> RestTemplateBuilder builder;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> <span class="function">RestTemplate <span class="title">restTemplate</span><span class="params">()</span></span>&#123;</span><br><span class="line">        <span class="comment">//通过RestTemplateBuilder生成RestTemplate</span></span><br><span class="line">        <span class="function"><span class="keyword">return</span> builder.<span class="title">build</span><span class="params">()</span></span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用RestTemplate</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>根据url获取WeatherResponse数据</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>@param url</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>@return</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">private WeatherResponse getWeatherResponse(<span class="built_in">String</span> url)&#123;</span><br><span class="line">    <span class="comment">//使用RestTemplate发送HTTP请求</span></span><br><span class="line">    ResponseEntity&lt;<span class="built_in">String</span>&gt; respString = restTemplate.getForEntity(url, <span class="built_in">String</span>.<span class="keyword">class</span>);</span><br><span class="line">    WeatherResponse result = <span class="keyword">null</span>;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将json格式的字符串转换为Java对象</span></span><br><span class="line">    ObjectMapper mapper = <span class="keyword">new</span> ObjectMapper();</span><br><span class="line">    <span class="keyword">if</span>(respString.getStatusCodeValue() == <span class="number">200</span>)&#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            result = mapper.readValue(respString.getBody(), WeatherResponse.<span class="keyword">class</span>);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JsonProcessingException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>运行结果<br><img src="/blog/images/20191114141217894.jpg" alt="天气预报免费数据来源"></p>
</li>
</ol>
<h3 id="使用Redis提升并发访问能力"><a href="#使用Redis提升并发访问能力" class="headerlink" title="使用Redis提升并发访问能力"></a>使用Redis提升并发访问能力</h3><ol>
<li><p>本系统存在的问题</p>
<blockquote>
<p>本系统是数据中介，强依赖第三方系统————延时问题<br>免费接口————访问次数限制问题<br>多次访问————对第三方接口服务器压力大</p>
</blockquote>
</li>
<li><p>使用Redis提升并发访问能力</p>
<blockquote>
<p>Why? Redis及时响应; Redis缓存指定时间内的数据，减少服务调用次数； </p>
</blockquote>
</li>
<li><p>如何应用Redis实现缓存数据？</p>
<blockquote>
<p>在获取天气数据的方法中，先去缓存中取数据，缓存中没有数据才调第三方接口获取，获取之后存储到缓存中</p>
</blockquote>
</li>
</ol>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Autowired</span></span><br><span class="line">private StringRedisTemplate stringRedisTemplate;</span><br><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>V1.0 根据url获取WeatherResponse数据</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>V2.0 使用Redis缓存数据</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>@param url</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet"> * </span>@return</span></span></span><br><span class="line"><span class="comment"><span class="markdown"> */</span></span></span><br><span class="line">private WeatherResponse getWeatherResponse(<span class="built_in">String</span> url)&#123;</span><br><span class="line">    WeatherResponse result = <span class="keyword">null</span>;</span><br><span class="line">    <span class="built_in">String</span> stringBody = <span class="keyword">null</span>;</span><br><span class="line">    ObjectMapper mapper = <span class="keyword">new</span> ObjectMapper();</span><br><span class="line">    <span class="comment">// 从缓存中取数据</span></span><br><span class="line">    ValueOperations&lt;<span class="built_in">String</span>, <span class="built_in">String</span>&gt; ops =  stringRedisTemplate.opsForValue();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//V2.0 先从缓存中取数据</span></span><br><span class="line">    <span class="keyword">if</span>(stringRedisTemplate.hasKey(url))&#123;</span><br><span class="line">        log.info(<span class="string">"Redis has data"</span>);</span><br><span class="line">        stringBody = ops.<span class="keyword">get</span>(url);</span><br><span class="line">    &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">        log.info(<span class="string">"Redis do not have data"</span>);</span><br><span class="line">        <span class="comment">//V1.0 使用RestTemplate发送HTTP请求</span></span><br><span class="line">        <span class="comment">//V2.0 //缓存中没有才调用服务接口获取数据，</span></span><br><span class="line">        ResponseEntity&lt;<span class="built_in">String</span>&gt; respString = restTemplate.getForEntity(url, <span class="built_in">String</span>.<span class="keyword">class</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">if</span>(respString.getStatusCodeValue() == <span class="number">200</span>)&#123;</span><br><span class="line">            stringBody = respString.getBody();</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="comment">//V2.0  将数据保存到缓存中：set(key,value,过期时间，时间单位)</span></span><br><span class="line">        ops.<span class="keyword">set</span>(url, stringBody, TIME_OUT, TimeUnit.SECONDS);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将json格式的字符串转换为Java对象</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        result = mapper.readValue(stringBody, WeatherResponse.<span class="keyword">class</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (JsonProcessingException e) &#123;</span><br><span class="line">        log.error(<span class="string">"Error!"</span>, e);</span><br><span class="line">    &#125;</span><br><span class="line">    </span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>运行结果如下图：<br><img src="/blog/images/20191115130316433.jpg" alt="运行结果"></p>
<p>下图为1.0版本的代码：<br><img src="/blog/images/20191115125905884.jpg" alt="下图为1.0版本的代码"></p>
<h3 id="实现天气数据的自动同步"><a href="#实现天气数据的自动同步" class="headerlink" title="实现天气数据的自动同步"></a>实现天气数据的自动同步</h3><blockquote>
<p>由于天气数据是必须依赖于第三方服务，所以我们使用Redis缓存来最大限度减少对第三方的依赖。<br>但用户访问本系统时才触发从第三方服务获取天气数据的动作，这个请求在实际中应该自动完成，这样可以减少用户响应时间。</p>
</blockquote>
<p><strong>定时任务————使用Quartz Scheduler定时器</strong></p>
<ol>
<li><p>引入 Spring Boot Quartz Starter依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!-- Spring Boot Quartz Starter已经集成了Quartz Scheduler --&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-quartz<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>编写定时任务类</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 同步天气数据的定时任务类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"></span><br><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">WeatherDataSyncJob</span> <span class="keyword">extends</span> <span class="title">QuartzJobBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void executeInternal(<span class="type">JobExecutionContext</span> jobExecutionContext) <span class="keyword">throws</span> <span class="type">JobExecutionException</span> &#123;</span><br><span class="line">        log.info(<span class="string">"WeatherDataSyncJob: executeInternal"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>编写定时任务配置类</p>
<figure class="highlight kotlin"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * Quartz配置类</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 配置Quartz需要2个Bean</span></span><br><span class="line"><span class="comment"> * JobDetail: 特定的一个Job</span></span><br><span class="line"><span class="comment"> * Trigger: 定义触发规则</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">QuartzConfiguration</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//JobDetail</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> JobDetail weatherDataSyncJobDetail()&#123;</span><br><span class="line">       <span class="comment">//通过JobBuilder来创建JobDetail</span></span><br><span class="line">       <span class="keyword">return</span> JobBuilder.newJob(WeatherDataSyncJob.<span class="keyword">class</span>)</span><br><span class="line">                 .withIdentity(<span class="string">"weatherDataSyncJob"</span>)</span><br><span class="line">                 .storeDurably().build();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//Trigger</span></span><br><span class="line">    <span class="meta">@Bean</span></span><br><span class="line">    <span class="keyword">public</span> Trigger weatherDataSyncTrigger()&#123;</span><br><span class="line">        <span class="comment">//定义定时规则：2s执行一次</span></span><br><span class="line">        SimpleScheduleBuilder scheduleBuilder =</span><br><span class="line">                SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(<span class="number">2</span>).repeatForever();</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> TriggerBuilder.newTrigger()</span><br><span class="line">                .forJob(weatherDataSyncJobDetail())</span><br><span class="line">                .withIdentity(<span class="string">"weatherDataSyncTrigger"</span>)</span><br><span class="line">                .withSchedule(scheduleBuilder).build();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>运行结果如下图：<br><img src="/blog/images/20191118130148706.jpg" alt="运行结果"></p>
<h3 id="获取城市数据完成天气数据的自动同步"><a href="#获取城市数据完成天气数据的自动同步" class="headerlink" title="获取城市数据完成天气数据的自动同步"></a>获取城市数据完成天气数据的自动同步</h3><p>在上一节，我们知道了如何使用Quartz Scheduler实现定时任务的执行，现在开始实现天气数据的自动同步的业务：</p>
<ol>
<li>获取城市数据列表并存储到本地的citylist.xml文件中<blockquote>
<p><a href="http://mobile.weather.com.cn/js/citylist.xml" target="_blank" rel="noopener">http://mobile.weather.com.cn/js/citylist.xml</a></p>
</blockquote>
</li>
</ol>
<blockquote>
<p>获取全国所有城市代码列表<br>方法一：XML接口根节点： <a href="http://flash.weather.com.cn/wmaps/xml/china.xmlXML接口主要作用是递归获取全国几千个县以上单位的城市代码，如：江苏的XML地址为：http://flash.weather.com.cn/wmaps/xml/shanghai.xml" target="_blank" rel="noopener">http://flash.weather.com.cn/wmaps/xml/china.xmlXML接口主要作用是递归获取全国几千个县以上单位的城市代码，如：江苏的XML地址为：http://flash.weather.com.cn/wmaps/xml/shanghai.xml</a> 苏州的XML地址为：<a href="http://flash.weather.com.cn/wmaps/xml/jiangsu.xml" target="_blank" rel="noopener">http://flash.weather.com.cn/wmaps/xml/jiangsu.xml</a> 上面页面获得太仓city code：101190408合成太仓天气信息地址：<a href="http://m.weather.com.cn/data/101190408.html" target="_blank" rel="noopener">http://m.weather.com.cn/data/101190408.html</a></p>
</blockquote>
<ol start="2">
<li>定义xml文件映射到的Bean类</li>
</ol>
<p>xml文件的格式为：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?xml version="1.0" encoding="UTF-8"?&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">c</span> <span class="attr">c1</span>=<span class="string">"0"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">d</span> <span class="attr">d1</span>=<span class="string">"101280101"</span> <span class="attr">d2</span>=<span class="string">"广州"</span> <span class="attr">d3</span>=<span class="string">"guangzhou"</span> <span class="attr">d4</span>=<span class="string">"广东"</span>/&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">d</span> <span class="attr">d1</span>=<span class="string">"101280102"</span> <span class="attr">d2</span>=<span class="string">"番禺"</span> <span class="attr">d3</span>=<span class="string">"panyu"</span> <span class="attr">d4</span>=<span class="string">"广东"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">c</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p>对应的Bean类是：</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * citylist.xml中城市数据对应的Bean类</span></span><br><span class="line"><span class="comment"> * &lt;d d1="101280101" d2="广州" d3="guangzhou" d4="广东"/&gt;</span></span><br><span class="line"><span class="comment"> *</span></span><br><span class="line"><span class="comment"> * 通过如下注解实现 映射xml文件到Java Bean</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="variable">@Data</span></span><br><span class="line"><span class="variable">@XmlRootElement</span>(name=<span class="string">"d"</span>) <span class="comment">//对应xml文件中的根标签</span></span><br><span class="line"><span class="variable">@XmlAccessorType</span>(XmlAccessType.FIELD) <span class="comment">//设置访问类型：按字段访问</span></span><br><span class="line">public class City &#123;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="variable">@XmlAttribute</span>(name=<span class="string">"d1"</span>)  <span class="comment">//对应xml文件中的属性</span></span><br><span class="line">    private String cityId;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@XmlAttribute</span>(name=<span class="string">"d2"</span>)</span><br><span class="line">    private String cityName;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@XmlAttribute</span>(name=<span class="string">"d3"</span>)</span><br><span class="line">    private String cityCode;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@XmlAttribute</span>(name=<span class="string">"d4"</span>)</span><br><span class="line">    private String province;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * citylist.xml中城市数据集合对应的Bean类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="variable">@Data</span></span><br><span class="line"><span class="variable">@XmlRootElement</span>(name=<span class="string">"c"</span>) <span class="comment">//对应xml文件中的根标签</span></span><br><span class="line"><span class="variable">@XmlAccessorType</span>(XmlAccessType.FIELD) <span class="comment">//设置访问类型：按字段访问</span></span><br><span class="line">public class CityList &#123;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@XmlElement</span>(name = <span class="string">"d"</span>)</span><br><span class="line">    private List&lt;City&gt; cityList;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<ol start="3">
<li><p>将xml文件解析为Java对象的工具类</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * 将xml文件转换为Java对象的工具类</span></span><br><span class="line"><span class="comment"> */</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">XmlBuilder</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">/**</span></span><br><span class="line"><span class="comment">     * 将xml字符串转换为指定的POJO对象</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> clazz</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@param</span> xmlStr</span></span><br><span class="line"><span class="comment">     * <span class="doctag">@return</span></span></span><br><span class="line"><span class="comment">     * <span class="doctag">@throws</span> Exception</span></span><br><span class="line"><span class="comment">     */</span></span><br><span class="line">    <span class="keyword">public</span> <span class="keyword">static</span> Object xmlStrToObj(<span class="class"><span class="keyword">Class</span>&lt;?&gt; <span class="title">clazz</span>, <span class="title">String</span> <span class="title">xmlStr</span>) <span class="title">throws</span> <span class="title">Exception</span></span>&#123;</span><br><span class="line">        Object xmlObjext = <span class="keyword">null</span>;</span><br><span class="line">        JAXBContext context = JAXBContext.newInstance(clazz);</span><br><span class="line">        <span class="comment">//将xml字符串解析为POJO对象</span></span><br><span class="line">        Unmarshaller unmarshaller = context.createUnmarshaller();</span><br><span class="line">        Reader reader = <span class="keyword">new</span> StringReader(xmlStr);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            xmlObjext = unmarshaller.unmarshal(reader);</span><br><span class="line">        &#125; <span class="keyword">catch</span> (JAXBException e) &#123;</span><br><span class="line">            e.printStackTrace();</span><br><span class="line">        &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">            <span class="keyword">if</span>(<span class="keyword">null</span> != reader) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    reader.close();</span><br><span class="line">                &#125; <span class="keyword">catch</span> (IOException e) &#123;</span><br><span class="line">                    e.printStackTrace();</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="keyword">return</span> xmlObjext;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>编写城市数据服务</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Service</span></span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">CityDataServiceImpl</span> <span class="keyword">implements</span> <span class="title">CityDataService</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>获取城市列表</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@return</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@throws Exception</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    public <span class="built_in">List</span>&lt;City&gt; getCityList() throws Exception &#123;</span><br><span class="line">        <span class="comment">//1. 读取xml文件</span></span><br><span class="line">        Resource resource = <span class="keyword">new</span> ClassPathResource(<span class="string">"cityList.xml"</span>);</span><br><span class="line">        BufferedReader br =</span><br><span class="line">                <span class="keyword">new</span> BufferedReader(<span class="keyword">new</span> InputStreamReader(resource.getInputStream(),<span class="string">"utf-8"</span>));</span><br><span class="line">        <span class="built_in">StringBuffer</span> stringBuffer = <span class="keyword">new</span> <span class="built_in">StringBuffer</span>();</span><br><span class="line">        <span class="built_in">String</span> line = <span class="string">""</span>;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">while</span> ((line = br.readLine()) != <span class="keyword">null</span>)&#123;</span><br><span class="line">            stringBuffer.append(line);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        br.close();</span><br><span class="line">        <span class="comment">//2. 解析xml数据为POJO对象</span></span><br><span class="line">        CityList cityList = (CityList)XmlBuilder.xmlStrToObj(CityList.<span class="keyword">class</span>, stringBuffer.toString());</span><br><span class="line">        <span class="keyword">return</span> cityList.getCityList();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>根据城市id同步天气数据</p>
<figure class="highlight dart"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"><span class="markdown">/**</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>根据城市id同步天气数据</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="bullet">     * </span>@param cityId</span></span></span><br><span class="line"><span class="comment"><span class="markdown"><span class="code">     */</span></span></span></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    public <span class="keyword">void</span> syncWeatherDataByCityId(<span class="built_in">String</span> cityId) &#123;</span><br><span class="line">        <span class="built_in">String</span> url = WEATHER_URL + <span class="string">"?citykey="</span> + cityId.trim();</span><br><span class="line">        saveWeatherDataToRedis(url);</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>自动同步功能完善</p>
<figure class="highlight scala"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Slf</span>4j</span><br><span class="line">public <span class="class"><span class="keyword">class</span> <span class="title">WeatherDataSyncJob</span> <span class="keyword">extends</span> <span class="title">QuartzJobBean</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">CityDataService</span> cityDataService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Autowired</span></span><br><span class="line">    <span class="keyword">private</span> <span class="type">WeatherDataService</span> weatherDataService;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> void executeInternal(<span class="type">JobExecutionContext</span> jobExecutionContext) <span class="keyword">throws</span> <span class="type">JobExecutionException</span> &#123;</span><br><span class="line">        log.info(<span class="string">"Weather Data Sync Job starting..."</span>);</span><br><span class="line">        <span class="comment">//1. 获取城市id列表</span></span><br><span class="line">        <span class="type">List</span>&lt;<span class="type">City</span>&gt; cityList = <span class="literal">null</span>;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            cityList = cityDataService.getCityList();</span><br><span class="line">        &#125; <span class="keyword">catch</span> (<span class="type">Exception</span> e) &#123;</span><br><span class="line">            log.error(<span class="string">"Exception!"</span>, e);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//2. 遍历列表，获取城市天气数据并保存到Redis中</span></span><br><span class="line">        <span class="keyword">for</span> (<span class="type">City</span> city:cityList) &#123;</span><br><span class="line">            <span class="type">String</span> cityId = city.getCityId();</span><br><span class="line">            log.info(<span class="string">"Weather Data Sync Job, cityId:"</span>+cityId);</span><br><span class="line">            weatherDataService.syncWeatherDataByCityId(cityId);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        log.info(<span class="string">"Weather Data Sync Job finished!"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>运行结果如下图：<br><img src="/blog/images/20191120175853773.jpg" alt="运行结果"></p>
<h3 id="前端访问UI页面-集成Thymeleaf"><a href="#前端访问UI页面-集成Thymeleaf" class="headerlink" title="前端访问UI页面-集成Thymeleaf"></a>前端访问UI页面-集成Thymeleaf</h3><ol>
<li><p>前端功能</p>
<blockquote>
<p>按照不同的城市进行查询；查询最近几天的天气信息；界面简洁、优雅(通过Bootstrap实现)</p>
</blockquote>
</li>
<li><p>接口：天气预报服务API</p>
<figure class="highlight awk"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="regexp">//</span>获取到该城市ID的天气预报信息</span><br><span class="line">GET <span class="regexp">/report/</span>cityId<span class="regexp">/&#123;cityId&#125;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>添加Thymeleaf依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--Thymeleaf--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>org.springframework.boot<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>spring-boot-starter-thymeleaf<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>编写返回前端页面数据的Controller</p>
<figure class="highlight less"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable">@RestController</span></span><br><span class="line"><span class="variable">@RequestMapping</span>(<span class="string">"/report"</span>)</span><br><span class="line">public class WeatherReportController &#123;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@Autowired</span></span><br><span class="line">    private WeatherReportService weatherReportService;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@Autowired</span></span><br><span class="line">    private CityDataService cityDataService;</span><br><span class="line"></span><br><span class="line">    <span class="variable">@RequestMapping</span>(<span class="string">"/cityId/&#123;cityId&#125;"</span>)</span><br><span class="line">    public ModelAndView getDataById(<span class="variable">@PathVariable</span>(<span class="string">"cityId"</span>) String cityId, Model model) throws Exception&#123;</span><br><span class="line">        <span class="selector-tag">model</span><span class="selector-class">.addAttribute</span>(<span class="string">"title"</span>,<span class="string">"aiolos的天气预报"</span>);</span><br><span class="line">        <span class="selector-tag">model</span><span class="selector-class">.addAttribute</span>(<span class="string">"cityId"</span>,cityId);</span><br><span class="line">        <span class="selector-tag">model</span><span class="selector-class">.addAttribute</span>(<span class="string">"cityList"</span>, cityDataService.getCityList());</span><br><span class="line">        <span class="selector-tag">model</span><span class="selector-class">.addAttribute</span>(<span class="string">"report"</span>, weatherReportService.getDataByCityId(cityId));</span><br><span class="line">        <span class="selector-tag">return</span> <span class="selector-tag">new</span> <span class="selector-tag">ModelAndView</span>(<span class="string">"weather/report"</span>,<span class="string">"reportModel"</span>,model);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
</li>
<li><p>使用Thymeleaf</p>
<figure class="highlight dust"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="xml"><span class="meta">&lt;!doctype html&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"zh-CN"</span> <span class="attr">xmlns:th</span>=<span class="string">"http://www.w3.org/1999/xhtml"</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"UTF-8"</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span></span></span></span><br><span class="line"><span class="xml">          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"&gt;</span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">http-equiv</span>=<span class="string">"X-UA-Compatible"</span> <span class="attr">content</span>=<span class="string">"ie=edge"</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>天气预报<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">h3</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;reportModel.title&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span><span class="tag">&lt;/<span class="name">h3</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">select</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">option</span> <span class="attr">th:each</span>=<span class="string">"city : $</span></span></span><span class="template-variable">&#123;reportModel.cityList&#125;</span><span class="xml"><span class="tag"><span class="string">"</span></span></span></span><br><span class="line"><span class="xml">                th:value="$</span><span class="template-variable">&#123;city.cityId&#125;</span><span class="xml">" th:text="$</span><span class="template-variable">&#123;city.cityName&#125;</span><span class="xml">"</span></span><br><span class="line"><span class="xml">                th:selected="$</span><span class="template-variable">&#123;city.cityId <span class="keyword">eq</span> reportModel.cityId&#125;</span><span class="xml">"&gt;<span class="tag">&lt;/<span class="name">option</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">select</span>&gt;</span></span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">h1</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;reportModel.report.city&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span>城市名称<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">        感冒指数：<span class="tag">&lt;<span class="name">span</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;reportModel.report.ganmao&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span><span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">        当前温度：<span class="tag">&lt;<span class="name">span</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;reportModel.report.wendu&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span><span class="tag">&lt;/<span class="name">span</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml"></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;<span class="name">div</span> <span class="attr">th:each</span>=<span class="string">"forecast : $</span></span></span><span class="template-variable">&#123;reportModel.report.forecast&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;<span class="name">p</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;forecast.date&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span>日期<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;<span class="name">p</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;forecast.type&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span>天气类型<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;<span class="name">p</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;forecast.high&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span>最高温度<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;<span class="name">p</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;forecast.low&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span>最低温度<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;<span class="name">p</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;forecast.fengli&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span>风力<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">            <span class="tag">&lt;<span class="name">p</span> <span class="attr">th:text</span>=<span class="string">"$</span></span></span><span class="template-variable">&#123;forecast.fengxiang&#125;</span><span class="xml"><span class="tag"><span class="string">"</span>&gt;</span>风向<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span><br><span class="line"><span class="xml">        <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">body</span>&gt;</span></span></span><br><span class="line"><span class="xml"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span></span><br></pre></td></tr></table></figure>

</li>
</ol>
<p>运行结果如下图：<br><img src="/blog/images/20191121092757906.jpg" alt="运行结果"></p>
<h3 id="前端访问UI页面-集成Bootstrap"><a href="#前端访问UI页面-集成Bootstrap" class="headerlink" title="前端访问UI页面-集成Bootstrap"></a>前端访问UI页面-集成Bootstrap</h3><p>Bootstrap官网：<a href="https://v4.bootcss.com/docs/4.3/getting-started/introduction/" target="_blank" rel="noopener">https://v4.bootcss.com/docs/4.3/getting-started/introduction/</a></p>
<ol>
<li><p>Bootstrap模板</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;!doctype html&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span> <span class="attr">lang</span>=<span class="string">"en"</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- Required meta tags --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">charset</span>=<span class="string">"utf-8"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">meta</span> <span class="attr">name</span>=<span class="string">"viewport"</span> <span class="attr">content</span>=<span class="string">"width=device-width, initial-scale=1, shrink-to-fit=no"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- Bootstrap CSS --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">href</span>=<span class="string">"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"</span> <span class="attr">integrity</span>=<span class="string">"sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"</span> <span class="attr">crossorigin</span>=<span class="string">"anonymous"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">title</span>&gt;</span>Hello, world!<span class="tag">&lt;/<span class="name">title</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">body</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">h1</span>&gt;</span>Hello, world!<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- Optional JavaScript --&gt;</span></span><br><span class="line">    <span class="comment">&lt;!-- jQuery first, then Popper.js, then Bootstrap JS --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://code.jquery.com/jquery-3.4.1.slim.min.js"</span> <span class="attr">integrity</span>=<span class="string">"sha384-J6qa4849blE2+poT4WnyKhv5vZF5SrPo0iEjwBvKU7imGFAV0wwj1yYfoRSJoZ+n"</span> <span class="attr">crossorigin</span>=<span class="string">"anonymous"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.15.0/umd/popper.min.js"</span> <span class="attr">integrity</span>=<span class="string">"sha384-L2pyEeut/H3mtgCBaUNw7KWzp5n9+4pDQiExs933/5QfaTh8YStYFFkOzSoXjlTb"</span> <span class="attr">crossorigin</span>=<span class="string">"anonymous"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"</span> <span class="attr">integrity</span>=<span class="string">"sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM"</span> <span class="attr">crossorigin</span>=<span class="string">"anonymous"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
</li>
<li><p>详细页面CSS布局见源代码，运行结果如下图：<br><img src="/blog/images/20191121131042251.jpg" alt="运行结果"></p>
</li>
</ol>
<h2 id="常见错误"><a href="#常见错误" class="headerlink" title="常见错误"></a>常见错误</h2><ol>
<li>使用RestTemplate报错：”Could not extract response: no suitable HttpMessageConverter found for response type [class com.aiolos.weather.vo.WeatherResponse] and content type [application/octet-stream]”</li>
</ol>
<blockquote>
<p>调用reseful接口传递的数据内容是json格式的字符串，返回的响应也是json格式的字符串。然而restTemplate.postForObject方法的请求参数RequestBean和返回参数ResponseBean却都是java类。是RestTemplate通过HttpMessageConverter自动帮我们做了转换的操作。<br>默认情况下RestTemplate自动帮我们注册了一组HttpMessageConverter用来处理一些不同的contentType的请求。<br>如StringHttpMessageConverter来处理text/plain;MappingJackson2HttpMessageConverter来处理application/json;MappingJackson2XmlHttpMessageConverter来处理application/xml。<br>你可以在org.springframework.http.converter包下找到所有spring帮我们实现好的转换器。<br>如果现有的转换器不能满足你的需求，你还可以实现org.springframework.http.converter.HttpMessageConverter接口自己写一个。<br>引用自：<a href="https://www.jianshu.com/p/90ec27b3b518" target="_blank" rel="noopener">https://www.jianshu.com/p/90ec27b3b518</a></p>
</blockquote>
<p>错误原因：根本原因是HTTP消息转换器HttpMessageConverter缺少MIME Type。</p>
<p>解决方法一： 见《天气预报系统开发》一节的第4小节，”将json格式的字符串转换为Java对象”部分的代码</p>
<p>解决方法二：见<a href="https://blog.csdn.net/qq_31424825/article/details/90270986" target="_blank" rel="noopener">https://blog.csdn.net/qq_31424825/article/details/90270986</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/blog/tags/Spring-Cloud天气项目微服务/" rel="tag"># Spring Cloud天气项目微服务</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2019/11/10/what-is-spring-IOC-2/" rel="next" title="Spring IOC二">
                <i class="fa fa-chevron-left"></i> Spring IOC二
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2019/11/21/spring-cloud-weather-2/" rel="prev" title="【二】从天气项目看Spring Cloud微服务治理——服务拆分与业务建模">
                【二】从天气项目看Spring Cloud微服务治理——服务拆分与业务建模 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name">aiolos</p>
              <p class="site-description motion-element" itemprop="description">Java Spring Hadoop 机器学习</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">126</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/blog/categories/index.html">
                  <span class="site-state-item-count">16</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/blog/tags/index.html">
                  <span class="site-state-item-count">33</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#本文中的关键技术点"><span class="nav-number">1.</span> <span class="nav-text">本文中的关键技术点</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#扩展学习"><span class="nav-number">2.</span> <span class="nav-text">扩展学习</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#微服务的基石——SpringBoot简介"><span class="nav-number">3.</span> <span class="nav-text">微服务的基石——SpringBoot简介</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#通过MockMvc进行web项目的单元测试"><span class="nav-number">3.1.</span> <span class="nav-text">通过MockMvc进行web项目的单元测试</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#运行springboot项目的三种方式"><span class="nav-number">3.2.</span> <span class="nav-text">运行springboot项目的三种方式</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#基于Springboot构建天气预报系统"><span class="nav-number">4.</span> <span class="nav-text">基于Springboot构建天气预报系统</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#天气预报单系统的功能"><span class="nav-number">4.1.</span> <span class="nav-text">天气预报单系统的功能</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#天气预报系统开发准备"><span class="nav-number">4.2.</span> <span class="nav-text">天气预报系统开发准备</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#使用Redis提升并发访问能力"><span class="nav-number">4.3.</span> <span class="nav-text">使用Redis提升并发访问能力</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#实现天气数据的自动同步"><span class="nav-number">4.4.</span> <span class="nav-text">实现天气数据的自动同步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#获取城市数据完成天气数据的自动同步"><span class="nav-number">4.5.</span> <span class="nav-text">获取城市数据完成天气数据的自动同步</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#前端访问UI页面-集成Thymeleaf"><span class="nav-number">4.6.</span> <span class="nav-text">前端访问UI页面-集成Thymeleaf</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#前端访问UI页面-集成Bootstrap"><span class="nav-number">4.7.</span> <span class="nav-text">前端访问UI页面-集成Bootstrap</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#常见错误"><span class="nav-number">5.</span> <span class="nav-text">常见错误</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">aiolos</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/blog/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  

</body>
</html>
